"""
A timer object, used to complete some set of actions before a timeout has
elapsed.

Copyright (c) 2009 Christopher Hesse
http://code.google.com/p/python-expect/
"""

import time


class Timer(object):
    """
    Timer class, after it's initialized with a timeout, it starts counting
    down immediately. timer.remaining tells you the number of seconds left,
    timer.elapsed is the number of seconds that have passed.
    
    timer.sleep(seconds) sleeps for some amount of time, just a convenience
    function to avoid importing the time module.
    """
    
    def __init__(self, timeout=0):
        self.timeout = timeout
        self.start_time = time.time()
    
    @property
    def elapsed(self):
        return time.time() - self.start_time
    
    @property
    def remaining(self):
        remaining = self.timeout - self.elapsed
        return remaining if remaining > 0 else 0
        
    def reset(self, new_timeout=None):
        self.start_time = time.time()
        if new_timeout is not None:
            self.timeout = new_timeout
        
    def sleep(self, seconds):
        time.sleep(seconds)